package com.farm.model.taobao.service;

import com.alibaba.fastjson.JSON;
import com.farm.model.product.dao.ProductDao;
import com.farm.model.product.entity.Product;
import com.farm.model.product.request.ProductRequest;
import com.farm.model.product.request.TaobaoPullRequest;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.NTbkItem;
import com.taobao.api.request.TbkItemGetRequest;
import com.taobao.api.response.TbkItemGetResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TaobaoService {

	Logger logger = LoggerFactory.getLogger(TaobaoService.class);

	public List<NTbkItem> invokingTaobao(TaobaoPullRequest taobaoPullRequest){
		String serverUrl = "http://gw.api.taobao.com/router/rest";
		String appKey = "25255015"; // 可替换为您的沙箱环境应用的AppKey
		String appSecret = "9bf8fd54cf5131068f3ff4150ab60c48"; // 可替换为您的沙箱环境应用的AppSecret
		String sessionKey = "6100a26f64862e9373c5be53e26869a99d165db8907480e92220917"; // 必须替换为沙箱账号授权得到的真实有效SessionKey

		TaobaoClient client = new DefaultTaobaoClient(serverUrl, appKey, appSecret);

		TbkItemGetRequest req = new TbkItemGetRequest();
		req.setFields("num_iid,title,pict_url,small_images,reserve_price,zk_final_price,user_type,provcity,item_url,seller_id,volume,nick");
		req.setQ(taobaoPullRequest.getSearchName());
		req.setCat(taobaoPullRequest.getCat());
		req.setItemloc(taobaoPullRequest.getItemloc());
		req.setSort(taobaoPullRequest.getSort());
		req.setIsTmall(taobaoPullRequest.getIsTmall());
		req.setIsOverseas(taobaoPullRequest.getIsOverseas());
		req.setStartPrice(taobaoPullRequest.getStartPrice().longValue());
		req.setEndPrice(taobaoPullRequest.getEndPrice().longValue());
		req.setStartTkRate(taobaoPullRequest.getStartTkRate().longValue());
		req.setEndTkRate(taobaoPullRequest.getEndTkRate().longValue());
		req.setPlatform(taobaoPullRequest.getPlatform().longValue());
		req.setPageNo(taobaoPullRequest.getPageNum());
		req.setPageSize(taobaoPullRequest.getPageSize());
		TbkItemGetResponse rsp = null;
		try {
			rsp = client.execute(req);
		} catch (ApiException e) {
			logger.warn(e.getMessage());
		}
		List<NTbkItem> nTbkItems = rsp.getResults();
		return  nTbkItems;
	}

}
